<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <title>Document1</title>
    <style type="text/css">
        * { margin: 0; padding: 0; }

        html, body { height: 100%; }

        .flex { display: flex; }

        .flex-row { flex-direction: row; justify-content: space-around; align-items: center; }

        .flex-column { flex-direction: column; justify-content: flex-start; align-items: center; }

        body { overflow: auto; background: #fff; }

        .title { width: 100%; align-items: center; }

        /*.title h1 { padding-bottom: 20px; font-size: 38px; color: #ffffff; text-shadow: 0 1px 3px #222222; }*/

        /*.title p { font-size: 18px; color: #f5f5f5; text-shadow: 0 1px 3px #565656; }*/

        .wrap { width: 100%; }

        .wrap .reference { position: relative; padding: 10px; background-color: rgba(255, 255, 255, 0); border-radius: 10px; box-shadow: 0 0 20px #a1a19f; }

        .wrap .reference img.face { display: block; width: 320px; height: auto; border-radius: 10px; }

        .wrap .reference img.toggle { position: absolute; right: 10px; top: 10px; width: 50px; height: 50px; }

        .wrap .scan video { background-color: rgba(0, 0, 0, .8); border-radius: 10px; }

        .wrap .control { justify-content: space-around; height: 456px; padding: 0 20px; }

        .wrap .control p { width: 160px; height: 60px; background-color: #f9f9f9; text-align: center; line-height: 60px; color: #ffffff; font-size: 24px; border-radius: 8px; cursor: pointer; box-shadow: -8px -8px 150px -8px #b2b3b5 inset, 0 0 5px #222222; text-shadow: 0 0 1px #222222; transition: .5s; }

        .wrap .control p:hover { box-shadow: -8px -8px 150px -8px #50c4f1 inset, 0 0 5px #ffffff; }

        .wrap .scan { position: relative; overflow: hidden; }

        .wrap .scan .strainer { position: absolute; top: 10px; width: 320px; z-index: 998; height: 3px; }

        .wrap .scan .strainer1 { position: absolute; top: 10px; width: 320px; z-index: 999; height: 3px; }

        .wrap .scan .capture { width: 320px; height: 320px; }

        .wrap .scan .strainer.on { background: linear-gradient(to left, transparent, #0bffb2, transparent); animation: scan 1s linear infinite; }

        .bg, .pane {
            width: 240px;
            height: 240px;
            margin: 40px auto;
            overflow: hidden;  /* 隐藏显示区域外的内容*/
        }

        .bg {
            position: relative;
            background: url(img/2.png) center center no-repeat;
            border: 1px solid #b0f9e4;
			background-size:100% 100%;
        }

        .pane {
            position: absolute;
            z-index: -1;
            background: url(img/4.png) center center no-repeat;
			background-size:100% 100%;
            animation: move 1.5s ease-in-out infinite ;
            -webkit-animation: move 1.5s ease-in-out infinite;
        }
        @keyframes move {
            from{top:-260px}  /*网格移动到显示区域的外面*/
            to{top:0}
        }
        -webkit-@keyframes move {
                    from{top:-260px}
                    to{top:0}
                }
        @keyframes scan {
            0% { top: 10px; }
            50% { top: 456px; }
            100% { top: 10px; }
        }

        .btn {
            display: block;
            margin: 20px auto;
            padding: 5px;
            background-color: #007aff;
            border: 0;
            color: #ffffff;
            height: 40px;
            width: 200px;
        }

    </style>
	<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <!--  <script type="text/javascript" src="js/vconsole.min.js"></script> -->
    <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js"></script>
</head>
<body style="background-color: #1f1f1f">
<div class="title flex flex-column">
    <div style="width: 1px;height: 100px;"></div>
    <!--<textarea id="base64" class="title" style="width: 80%"></textarea>-->
</div>
<div class="wrap flex flex-row">
    <div class="control flex flex-column" style="display: none;">
        <p class="open">开启摄像头</p>
        <p class="recognition">显示到Canvas</p>
        <p class="close">关闭摄像头</p>
    </div>
    <div class="scan reference">

        <div class="strainer1">
            <div class="bg">
                <div class="pane"></div>
            </div>
        </div>
        <video id="video" class="capture" width="320" height="320" src="" muted="true"></video>
		
    </div>

</div>
<div class="title flex flex-column" dislpay="none">
    <!-- <button display="none" class="btn" type="button" id="postMessage">postMessage</button> -->
	<canvas style="display:none;" id="canvas" width="320" height="320"></canvas>
</div>
<script type="text/javascript">
    var buffer;
    var control = document.querySelector(".control");
	var video = document.getElementById('video');
	var canvas = document.getElementById('canvas');
	var context = canvas.getContext('2d');
	var count = 0,successFace = false;
   

	var your_client_id = '替换成你的';
	var your_client_secret = '替换成你的';

    function closeCamera(){
		try{
			buffer&&buffer.getTracks()[1].stop();//关闭摄像头
		}catch(e){
			//TODO handle the exception
			return;
		}
        
    }
	
	
    (function () {
		var hash = window.location.hash.substring(1);
		// console.log(hash);
		var reqData = {};
		try {
			reqData = JSON.parse(decodeURIComponent(hash));
		} catch (error) {
			reqData = JSON.parse(hash);
		}
		window.addEventListener("DOMContentLoaded", function() {
			// Grab elements, create settings, etc.
			var mediaConfig =  { 
				video: true
			};
			var errBack = function(e) {
				console.log('An error has occurred!', e)
			};
			console.log("start");
			
		
			// Put video listeners into place
			if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
				navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
					// video.src = window.URL.createObjectURL(stream);
					video.srcObject = stream;
					video.play();
					buffer = stream;
				});
			}
			/* Legacy code below! */
			else if(navigator.getUserMedia) { // Standard
				navigator.getUserMedia(mediaConfig, function(stream) {
					video.src = stream;
					video.play();
					buffer = stream;
				}, errBack);
			} else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
				navigator.mozGetUserMedia(mediaConfig, function(stream){
					video.src = window.URL.createObjectURL(stream);
					video.play();
					buffer = stream;
				}, errBack);
			} else if(navigator.msGetUserMedia) { // Mozilla-prefixed
				navigator.msGetUserMedia(mediaConfig, function(stream){
					video.src = window.URL.createObjectURL(stream);
					video.play();
					buffer = stream;
				}, errBack);
			} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
				navigator.webkitGetUserMedia(mediaConfig, function(stream){
					video.src = window.webkitURL.createObjectURL(stream);
					video.play();
					buffer = stream;
				}, errBack);
			}
		}, false);
		console.log("UserMedia");
		document.addEventListener('UniAppJSBridgeReady', function() {
		//获取access_token
		console.log("获取access_token");
		console.log('photo:'+reqData.photo);
		var baiduAccessTokenApi = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+your_client_id+'&client_secret='+your_client_secret;
		$.ajax({
			url:baiduAccessTokenApi,
			method:'GET',
			dataType:'json',
			success(res){
				var access_token = res.access_token;
				matchFace(access_token,reqData);
			},
			complete(){
				count++;
				if(successFace||count>30)
				{
					console.log("successFace!");
					closeCamera();
					uni.reLaunch({
						url:'/pages/newMain/newMain?cheakFace='+successFace
					})
				}
			}
		})
		
		function matchFace(access_token,reqData)
		{
			var baiduApi = 'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token='+access_token;
			send();
			function send(){
				console.log('count:'+count)
				$.ajax({
					url:baiduApi,
					contentType: "application/json",
					method:'POST',
					data:JSON.stringify([{
						  "image":""+reqData.photo,
						  "image_type":"BASE64",
						  "face_type":"LIVE",
						  "quality_control":"LOW",
						  "liveness_control":"NORMAL"
						},{
						  "image":""+getImage(),
						  "image_type":"BASE64",
						  "face_type":"LIVE",
						  "quality_control":"LOW",
						  "liveness_control":"NORMAL"
						}]),
					dataType:'json',
					timeout:7000,
					success(data){
						console.log(JSON.stringify(data))
						if(data.error_code ==0 && data.result.score >= 75 )
						{
							successFace = true;
							goBackPage();
						} else {
							// send()
							$.ajax({
								url:baiduAccessTokenApi,
								method:'GET',
								dataType:'json',
								success(res){
									baiduApi = 'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token='+ res.access_token;
								},
								complete(){
									count++;
									goBackPage();
									send();
								}
							})
						}
					},
					fail(){
						send();
					}
				})
			}	
		}
	});
    })();

	function goBackPage(){
		if(successFace||count>30)
		{
			console.log("successFace!");
			closeCamera();
			uni.reLaunch({
				url:'/pages/index/index?cheakFace='+successFace
			})
		}
	}

    function getImage() {
        context.drawImage(video,0,0,320,320);
        // 把画布的内容转换为base64编码格式的图片
        var data = canvas.toDataURL( 'image/png', 1 );  //1表示质量(无损压缩)
        return data.replace('data:image/png;base64,','');
    }
</script>
</body>
</html>
